package timing.ukulele.gateway.component;

import com.alibaba.fastjson2.JSON;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.boot.CommandLineRunner;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import timing.ukulele.gateway.config.properties.NacosGatewayProperties;

import java.util.List;
import java.util.concurrent.Executor;

@Component
public class DynamicRouteServiceImplByNacos implements CommandLineRunner {
    private final DynamicRouteServiceImpl dynamicRouteService;
    private final NacosGatewayProperties nacosGatewayProperties;

    public DynamicRouteServiceImplByNacos(DynamicRouteServiceImpl dynamicRouteService, NacosGatewayProperties nacosGatewayProperties) {
        this.dynamicRouteService = dynamicRouteService;
        this.nacosGatewayProperties = nacosGatewayProperties;
    }

    /**
     * 监听Nacos Service下发的动态了路由配置
     */
    public void dynamicRouteByNacosListener() {
        try {
            ConfigService configService = NacosFactory.createConfigService(nacosGatewayProperties.getAddress());
            // 程序启动的时候就从配置中心中读取路由配置信息
            String content = configService.getConfig(nacosGatewayProperties.getDataId(), nacosGatewayProperties.getGroupId(), nacosGatewayProperties.getTimeout());
            System.out.println(content);
            // 转成json
            List<RouteDefinition> list = JSON.parseArray(content, RouteDefinition.class);
            if (!CollectionUtils.isEmpty(list)) {
                dynamicRouteService.updateBatch(list);
            }
            // 添加配置信息变更监听
            configService.addListener(nacosGatewayProperties.getDataId(), nacosGatewayProperties.getGroupId(), new Listener() {
                @Override
                public Executor getExecutor() {
                    return null;
                }

                @Override
                public void receiveConfigInfo(String configInfo) {
                    System.out.println(configInfo);
                    List<RouteDefinition> list = JSON.parseArray(configInfo, RouteDefinition.class);
                    dynamicRouteService.updateBatch(list);
                }
            });
        } catch (NacosException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run(String... args) {
        dynamicRouteByNacosListener();
    }
}
